<?php

namespace AppVue\Http\Controllers;

use AppVue\Http\Models\ResponseResult;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class UploadFileController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin');
    }

    public function uplaodImage(Request $request) {
        return $this->getImg($request);
    }

    public function uploadImg(Request $request)
    {
        $result = json_decode($this->getImg($request));
        if ($result->success == true) {
            return [
                'url' => $result->data,
                'id' => Str::random(32)
            ];
        }
        return $result;
    }

    /**
     * @param Request $request
     * @return string
     */
    public function getImg(Request $request) {
        if ($request->file('file')->isFile()) {
            $file = $request->file('file');
            $md5file = md5_file($file);
            if($file->isValid()){
                $extension = $file->getClientOriginalExtension();
                $newName = $md5file.".".$extension;
                $date = date('Ym');
                $path = '/'.$file->move('uploads/img/'.$date,$newName);
                return ResponseResult::success($path);
            }
        }
        return ResponseResult::error(0, 'Not');
    }
}
